<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/2
 * Time: 18:03
 */

namespace App\Repository\Db;
use App\Model\TaoCang;
use App\Exceptions\ValidateException;
use App\Repository\Contracts\TaoCangInterface;
use Illuminate\Support\Facades\DB;

class TaoCangRepository extends Repository implements TaoCangInterface
{

    protected $rules = [
        'created' => [
            'title' => 'required|min:2|max:64',
            'discount' => 'required',
            'goods_arr' => 'required'
        ],
        'updated' => [
            'title' => 'required|min:2|max:64',
            'discount' => 'required',
            'goods_arr' => 'required'
        ]
    ];

    protected $messages = [
        'title.required' => "套餐名称不能为空",
        'discount.required' => "套餐折扣率或满减金额不能为空！",
        'goods_arr.required' => "必须选择商品！"
    ];

    protected function modelName()
    {
        return 'App\Model\TaoCang';
    }

    public function detail($id)
    {
        if (env('DIRECT_SALE')) {
            return $this->findBy('category_id', $id);
        }

        return $this->findBy('id', $id);
    }

    public function created(array $data)
    {
        if (env('DIRECT_SALE')) {
            throw new ValidateException('没有权限操作');
        }
        $this->validate($data, 'created');
        $lastId = $this->save($data);
        $lastId && $this->update(['id' => $lastId], $lastId, 'id');
        return $lastId;
    }

    public function lists($limit, $page, $map = [])
    {
        $query = $this->searchMap($map);
        $total = $query->count();
        $data = $query->orderBy('id', 'desc')->simplePaginate($limit, ['*'], 'page', $page);
        $list=$data->toArray();
        $lists=[];
        foreach ($list['data'] as $key=>&$row){
            $goods_arr=explode(',',$row['goods_arr']);
            //获取套餐商品名称
            $goods_list=DB::table('goods')->whereIn('id', $goods_arr)->get(['zh_name'])->toArray();
            $title=[];
            foreach ($goods_list as $key=>$value){
                $title[$key]=$value['zh_name'];
            }
            $row['goods_name_arr']=implode(',',$title);
        }

        //print_r($lists);exit;
        return $this->simplePaginate('list', $list['data'], $total, ceil($total/$limit), $page);
    }

    public function updated($id, array $data)
    {
        if (env('DIRECT_SALE')) {
            throw new ValidateException('没有权限操作');
        }
        $this->validate($data, 'updated', ['name' => $id]);

        return $this->update($data, $id, 'id');
    }

    public function findIdForFirst()
    {
        return $this->model->orderBy('updated_at', 'desc')->limit(1)->get()->toArray();
    }
}